package cn.wk.libs4a.view.adview;

import android.content.Context;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.widget.ImageView;
import cn.wk.libs4a.WKApplication;

public class GalleryImageView extends ImageView {
	private int defaultImageRes;
	private String url;
	private Context mContext;

	private Bitmap bitmap;

	/**
	 * 获取全局APP
	 */
	public WKApplication app() {
		return (WKApplication) mContext.getApplicationContext();
	}

	public GalleryImageView(Context context) {
		super(context);
		init(context);
	}

	public GalleryImageView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		init(context);
	}

	public GalleryImageView(Context context, AttributeSet attrs) {
		super(context, attrs);
		init(context);
	}

	public void init(Context context) {
		this.mContext = context;
	}

	public void setDefault(int resId) {
		defaultImageRes = resId;
	}

	public void setUrl(String imageUrl) {
		url = imageUrl;
	}

	@Override
	public void setImageBitmap(Bitmap bm) {
		if (bm != null) {
			bitmap = bm;
		}
		super.setImageBitmap(bm);
	}

	public void recycle(boolean showDefault) {
		if (showDefault) {
			if (defaultImageRes == 0) {
				setImageBitmap(null);
			} else {
				setImageResource(defaultImageRes);
			}
		}
		if (bitmap != null && !bitmap.isRecycled()) {
			bitmap.recycle();
			bitmap = null;
		}
	}

	public void reload() {
		if (!TextUtils.isEmpty(url)) {
			if (defaultImageRes == 0) {
				setImageBitmap(null);
			} else {
				setImageResource(defaultImageRes);
			}
			app().imageLoader.displayImage(url, this, app().options);
		}
	}

}
